Step 24: Bookmark DAO with Mongoose ODM
Update the src/data/BookmarkDAO.js file:
import Bookmark from "../model/Bookmark.js";
class BookmarkDAO {
// return the created bookmark
async create({ title, url }) {
const bookmark = await Bookmark.create({ title, url });
return bookmark;
}
// return all bookmarks
async readAll({ title, url }) {
const filter = {};
if (title) {
filter.title = title;
}
if (url) {
filter.url = url;
}
const bookmarks = await Bookmark.find(filter);
return bookmarks;
}
// return the bookmark with the given id
// return null if id does not exist in our database
async read(id) {
const bookmark = await Bookmark.findById(id);
return bookmark;
}
// return the updated bookmark
// return null if id does not exist in our database
async update({ id, title, url }) {
const bookmark = await Bookmark.findByIdAndUpdate(
id,
{ title, url },
{ new: true, runValidators: true }
);
return bookmark;
}
// return the deleted bookmark
// return null if id does not exist in our database
async delete(id) {
const bookmark = await Bookmark.findByIdAndDelete(id);
return bookmark;
}
}
export default BookmarkDAO;
Notes:
- The
createmethod allows you to create documents of that model. As an argument, it takes an object representing the data to be saved in the database. It throws an error if it encounters any errors while creating a document. - The
findmethod takes an optional parameter, a filter, which can be used to search for notes that match the given attribute values. If we want to receive all notes, we can callfindwith no argument or with an empty filter object. - If there are no "bookmarks" in the database, or there is no match for the filter we have provided, the
findmethod returns an empty array. - The first argument to
findByIdAndUpdateis the ID of a bookmark in our database to be updated. Ifiddoes not match an existing bookmark, thefindByIdAndUpdatewill returnnull. - The second argument to
findByIdAndUpdateis an object containing the new attributes (and their values) which are to replace the existing attribute values of the bookmark to be updated. If any of these are undefined, the attribute will not change (so we don't need if statements to guard against this scenario) - The third argument to
findByIdAndUpdateis an “option” object. The first option isnew: truewhich changes the default behavior offindByIdAndUpdateto return the updated note (instead of the original one). The second option isrunValidators: truethat changes the default behavior offindByIdAndUpdateto force running validators on new attributes. If validation fails, thefindByIdAndUpdateoperation throws an error. - The
findByIdAndDeletewill delete and return the deleted note if theidexists in the database. Otherwise, it will returnnull.